﻿using System.ComponentModel;

namespace Organizer.ViewModel
{
    using System;
    using System.Linq.Expressions;

    public abstract class BaseViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify that a property changed
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region INotifyPropertyChanging Members

        public event PropertyChangingEventHandler PropertyChanging;

        // Used to notify that a property is about to change
        protected void NotifyPropertyChanging(string propertyName)
        {
            if (PropertyChanging != null)
            {
                PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
            }
        }

        #endregion

        protected void NotifyPropertyChanged<T>(Expression<Func<T>> property)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var expression = property.Body as MemberExpression;
                if (expression == null)
                {
                    throw new NotSupportedException("Invalid expression passed. Only property member should be selected.");
                }

                handler(this, new PropertyChangedEventArgs(expression.Member.Name));
            }
        }

        protected void NotifyPropertyChanging<T>(Expression<Func<T>> property)
        {
            PropertyChangingEventHandler handler = this.PropertyChanging;
            if (handler != null)
            {
                var expression = property.Body as MemberExpression;
                if (expression == null)
                {
                    throw new NotSupportedException("Invalid expression passed. Only property member should be selected.");
                }

                handler(this, new PropertyChangingEventArgs(expression.Member.Name));
            }
        }

        public enum State { Edit, ManageSelection, Normal };
    }
}
